package com.yunda.nebula.gateway.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.regex.Pattern;

/**
 * @author xiongbiao
 * @date 2020/3/2
 */
public class MyLocalDateTimeDeserializer extends LocalDateTimeDeserializer {

    private Pattern timeStamp =  Pattern.compile("^[0-9]*$");

    private static final DateTimeFormatter DEFAULT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE_TIME;


    public MyLocalDateTimeDeserializer(DateTimeFormatter formatter) {
        super(formatter);
    }

    @Override
    public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
        String string = parser.getText().trim();
        if(timeStamp.matcher(string).matches()){
            if(string.length()==13){
                string = string.substring(0,10);
            }
           return LocalDateTime.ofEpochSecond(Long.parseLong(string),0, ZoneOffset.ofHours(8));
        }else if(string.indexOf('T')!=-1){
            return LocalDateTime.parse(string, DEFAULT_FORMATTER);
        }else{
            return super.deserialize(parser, context);
        }
    }
}
